package com.cn.wanxi.util;

import com.cn.wanxi.dao.IUserDao;
import com.cn.wanxi.dao.impl.UserDaoImpl;
import com.cn.wanxi.model.UserModel;

import java.sql.*;

public class JDBCUtils {
    private static String URL = "jdbc:mysql://localhost:3306/high_tech?serverTimezone=GMT%2B8&characterEncoding=utf8";
    private static String USERNAME = "root";
    private static String PASSWORD = "root";
    private static String DRIVER = "com.mysql.cj.jdbc.Driver";

    private static Connection conn = null;
    private static PreparedStatement pstmt = null;
    private static ResultSet rs;

    public static Connection getConnection() {
        try {
            Class.forName(DRIVER);
            if (conn == null)
                return conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int excute(String sql) {
        getConnection();
        int result = 0;
        try {
            pstmt = conn.prepareStatement(sql);
            result = pstmt.executeUpdate();
            if (result > 0)
                System.out.println("数据库操作成功！");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        System.out.println("result="+result);
        return result;
    }

    public static void close() {
        try {
            if (conn != null) {
                conn.close();
                conn = null;
            }
            if (pstmt != null) {
                pstmt.close();
                pstmt = null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static ResultSet getResultSet(String sql) {
        getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static void main(String[] args) {
//        System.out.println(JDBCUtils.getConnection());
        IUserDao userDao = new UserDaoImpl();
        UserModel userModel = userDao.getUser(1);
        userModel.setUsername("username");
//        userModel.setPassword("007");
//        userDao.addUser(userModel);
//        userModel.setId(1);
        userModel.setIntro("im good boy");
        userDao.updateUser(userModel);
        System.out.println(userDao.getUser(1));
    }
}
